#!/usr/bin/env python
# encoding: utf-8


from app.views.api import route_api
from  flask import request,jsonify
import json

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicFavorite
from app.model import ElectronicFavoriteItem

from app.common.libs.Logging import logger
from app.common.libs.Helper import getCurrentDate, getFormatDate
from app.common.libs.UserService import UserService

@route_api.route("/electronic/favorite/add",methods = [ "GET","POST" ])
def ElectronicFavoriteAdd():
    resp = { 'code':20000,'message':'收藏夹创建成功~', 'data':{}}
    req = request.values

    name = req['name'] if 'name' in req else ''

    if not name:
        resp['code'] = -1
        resp['message'] = '请填写名称'
        return jsonify( resp )

    favorite_info =  ElectronicFavorite.query.filter_by( name = name  ).first()
    if favorite_info:
        resp['code'] = -1
        resp['message'] = '收藏夹已存在~'
        return jsonify( resp )

    user_info = UserService.getUserInfo(request)

    favorite_model = ElectronicFavorite()
    favorite_model.name = name
    favorite_model.user_id = user_info.id
    favorite_model.created_time = favorite_model.updated_time = getCurrentDate()
    db.session.add(favorite_model)

    db.session.commit()

    return jsonify( resp )

@route_api.route("/electronic/favorite/delete",methods = [ "GET","POST" ])
def ElectronicFavoriteDelete():
    resp = { 'code':20000,'message':'收藏夹删除成功~', 'data':{}}
    req = request.values

    name = req['name'] if 'name' in req else ''
    if not name:
        resp['code'] = -1
        resp['message'] = '未选中删除'
        return jsonify( resp )

    user_info = UserService.getUserInfo(request)
    favorite_info =  db.session.query(ElectronicFavorite)\
                        .filter(ElectronicFavorite.name == name)\
                        .filter(ElectronicFavorite.user_id == user_info.id)\
                        .first()
    ElectronicFavoriteItem.query.filter_by( electronic_favorite_id = favorite_info.id ).delete()
    db.session.delete(favorite_info)
    db.session.commit()

    return jsonify( resp )

@route_api.route("/electronic/favorite/list",methods = [ "GET","POST" ])
def ElectronicFavoriteList():
    resp = { 'code':20000,'message':'查询成功~', 'data':{}}

    user_info = UserService.getUserInfo(request)

    favorite_list =  ElectronicFavorite.query.filter_by( user_id = user_info.id ).all()
    items = [f.name for f in favorite_list]
    #  if not favorite_list:
        #  resp['code'] = -1
        #  resp['message'] = '未创建收藏夹~'
        #  return jsonify( resp )
    resp['data']['items'] = items

    return jsonify( resp )

@route_api.route("/electronic/favorite/item/add",methods = [ "GET","POST" ])
def ElectronicFavoriteItemAdd():
    resp = { 'code':20000,'message':'添加成功~', 'data':{}}
    req = request.values

    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '未选择元器件~'
        return jsonify( resp )

    name = req['name'] if 'name' in req else ''
    if not name:
        resp['code'] = -1
        resp['message'] = '未选择收藏夹~'
        return jsonify( resp )

    electronic_info = Electronic.query.filter_by( sn = sn ).first()

    user_info = UserService.getUserInfo(request)

    favorite_info = ElectronicFavorite.query.filter_by( name = name, user_id = user_info.id ).first()

    favorite_item = ElectronicFavoriteItem.query.filter_by(electronic_favorite_id = favorite_info.id,
                                                            electronic_id = electronic_info.id,
                                                            user_id = user_info.id ).first()
    if favorite_item:
        resp['code'] = -1
        resp['message'] = '当前元器件已添加在收藏夹[%s]中~'%name
        return jsonify( resp )

    favorite_item_model = ElectronicFavoriteItem()
    favorite_item_model.user_id = user_info.id
    favorite_item_model.electronic_id = electronic_info.id
    favorite_item_model.electronic_favorite_id = favorite_info.id
    favorite_item_model.count = 1
    favorite_item_model.status = 1
    favorite_item_model.created_time = favorite_item_model.updated_time = getCurrentDate()
    db.session.add(favorite_item_model)
    db.session.commit()

    return jsonify( resp )

@route_api.route("/electronic/favorite/item/delete",methods = [ "GET","POST" ])
def ElectronicFavoriteItemDelete():
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    req = request.values

    sn = req['sn'] if 'sn' in req else ''
    if not sn:
        resp['code'] = -1
        resp['message'] = '未选择元器件~'
        return jsonify( resp )

    name = req['name'] if 'name' in req else ''
    if not name:
        resp['code'] = -1
        resp['message'] = '未选择收藏夹~'
        return jsonify( resp )

    electronic_info = Electronic.query.filter_by( sn = sn ).first()
    user_info = UserService.getUserInfo(request)
    favorite_info = ElectronicFavorite.query.filter_by( name = name, user_id = user_info.id ).first()

    ElectronicFavoriteItem.query.filter_by(electronic_favorite_id = favorite_info.id,
                                           electronic_id = electronic_info.id,
                                           user_id = user_info.id ).delete()

    db.session.commit()

    return jsonify( resp )

@route_api.route("/electronic/favorite/item/list",methods = [ "GET","POST" ])
def ElectronicFavoriteItemList():
    resp = { 'code':20000,'message':'添加成功~', 'data':{}}
    req = request.values
    name = req['name'] if 'name' in req else ''
    user_info = UserService.getUserInfo(request)
    favorite_items = db.session.query(Electronic, ElectronicFavoriteItem)\
        .filter(ElectronicFavoriteItem.electronic_id == Electronic.id)\
        .filter(ElectronicFavoriteItem.user_id == user_info.id)\
        .filter(ElectronicFavoriteItem.electronic_favorite_id == ElectronicFavorite.id)\
        .filter(ElectronicFavorite.name == name)\
        .all()
    items = []
    for electronic, favorite_item in favorite_items:
        items.append({
            'id':favorite_item.id,
            'electronic_id':electronic.id,
            'sn':electronic.sn,
            'name':electronic.name,
            'package':electronic.package,
            'price':str(electronic.price),
            'stock':electronic.stock,
            'count':favorite_item.count,
            'time':getFormatDate(favorite_item.created_time)
        })
    resp['data']['items'] = items

    return jsonify( resp )

@route_api.route("/electronic/favorite/item/update",methods = [ "GET","POST" ])
def ElectronicFavoriteItemUpdate():
    resp = { 'code':20000,'message':'更新成功~', 'data':{}}
    req = request.values
    electronics = req['electronics'] if 'electronics' in req else None
    if electronics is None:
        resp['code'] = -1
        resp['message'] = '未选择元器件~'
        return jsonify( resp )
    items = json.loads(electronics)
    for item in items:
        item_info = ElectronicFavoriteItem.query.filter_by( id = item['id']).first()
        item_info.count = int(item['count'])
    db.session.commit()
    return jsonify( resp )

